/**
 * 载入项目引导文件
 */
require('./bootstrap');

let box;//弹窗对象
var loadbox;//loading对象
var zTree;//zTree对象

$(document).ready(() => {
    let tableOptions = utils.bootstraptableOptions;
    //请求后台的URL
    tableOptions.url = page_params.url_list;
    //搜索参数
    tableOptions.queryParams = function (params) {//传递参数（*）
        //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        var temp = {
            //limit: params.limit,   //页面大小
            //offset: params.offset,
            pageSize:params.pageSize,
            page:params.pageNumber,
            subscribe_scene:$("#subscribe_scene").val(),
            openid:$("#openid").val(),
            sex:$("#sex").val(),
            keyword:$("#keyword").val(),
        };
        return temp;
    };
    tableOptions.rowStyle = function(row, index){
        var style = "";
        if (row.is_lock){
            style = 'danger';
        }
        return {classes:style};
    }
    tableOptions.columns = [
        {field:'checkbox',checkbox:'true'},
        {field: 'user_id',title: '#'},
        {field: 'openid',title: 'OPENID'},
        {field: 'nickname',title: '昵称'},
        {field: 'sex_name',title: '性别'},
        {
            field: 'headimgurl',title: '头像',
            formatter:function (value, row, index) {
                if (value){
                    return '<img alt="image" class="img-circle img-sm" src="' + value + '">';
                }
            }
        },
        {field: 'language',title: '语言',visible:false,},
        {field: 'country',title: '国家',visible:false,},
        {field: 'province',title: '省份',visible:false,},
        {field: 'city',title: '城市',visible:false,},
        {field: 'first_subscribe_time',title: '首次关注时间',visible:false,},

        {field: 'remark',title: '备注',},
        {field: 'subscribe_scene_name',title: '关注场景',visible:false,},
        {
            field: 'tagname_list',title: '标签',
            formatter:function (value, row, index) {
                let tagnames = [];
                if (value){
                    _.each(value, function (tagname) {
                        tagnames.push('<span class="label label-warning">' + tagname + '</span>');
                    });
                }
                return tagnames.join("\r\n");
            }
        },
        {
            field: 'subscribe',title: '是否关注',
            formatter:function (value, row, index) {
                if (value == 1){
                    return '<span class="label label-info">已关注</span>';
                }else{
                    return '<span class="label label-warning">未关注</span>';
                }
            }
        },
        {
            field: 'is_lock',title: '是否拉黑',
            formatter:function (value, row, index) {
                if (value == 1){
                    return '<span class="label label-danger">已拉黑</span>';
                }else{
                    return '<span class="label label-success">正常</span>';
                }
            }
        },
        {
            field: 'operate',
            title: '操作',
            formatter: function (value, row, index) {
                let buttons = [];
                if (page_params.url_setremark){
                    buttons.push('<button class="btn btn-primary btn-sm btn-setremark"><i class="fa fa-book"></i> 备注</button>');
                }
                if (page_params.url_settag){
                    buttons.push('<button class="btn btn-primary btn-sm btn-settag"><i class="fa fa-tag"></i> 设标签</button>');
                }
                if (page_params.url_setblack){
                    if (row.is_lock){
                        buttons.push('<button class="btn btn-success btn-sm btn-setblack"><i class="fa fa-unlock"></i> 恢复</button>');
                    }else{
                        buttons.push('<button class="btn btn-danger btn-sm btn-setblack"><i class="fa fa-lock"></i> 拉黑</button>');
                    }
                }
                return buttons.join("\r\n");
            },//自定义方法，添加操作按钮
            events : {
                'click .btn-setremark':function (e, value, row, index) {
                    $("#box-remark form").resetForm();
                    $('#box-remark form').attr('action', page_params.url_setremark);
                    $("#box-remark input[name='openid']").val(row.openid);
                    $("#box-remark input[name='remark']").val(row.remark);
                    box = layer.open({
                        type: 1,
                        title: '设置备注',
                        anim: 2,
                        shadeClose: true, //开启遮罩关闭
                        skin: 'layui-layer-molv', //加上边框
                        area: ['500px', '200px'], //宽高
                        content: $('#box-remark')
                    });
                },
                'click .btn-settag': function (e, value, row, index) {
                    $("#box-tag form").resetForm();
                    $("#box-tag form").attr('action', page_params.url_settag);
                    $("#box-tag input[name='openids']").val(row.openid);
                    //取消选中
                    zTree.checkAllNodes(false);
                    //设置部分选中
                    if (row.tagid_list.length > 0){
                        _.each(row.tagid_list, function(tagid, i){
                            let node = zTree.getNodeByParam("wx_tag_id", tagid);
                            if (node){
                                zTree.checkNode(node, true, true);
                            }
                        });
                    }

                    box = layer.open({
                        type: 1,
                        title: '设置标签',
                        anim: 2,
                        shadeClose: true, //开启遮罩关闭
                        skin: 'layui-layer-molv', //加上边框
                        area: ['500px', '400px'], //宽高
                        content: $('#box-tag')
                    });
                    return false;
                },
                'click .btn-setblack': function (e, value, row, index) {
                    var openids = [];
                    openids.push(row.openid);
                    setBlack(openids, !row.is_lock)
                }
            }
        },
    ];
    let table = $("#table").bootstrapTable(tableOptions);
    //设置zetree
    var setting = {
        check:{
            enable:true
        },
        data: {
            key:{
                name:'tag_name',
            },
            simpleData: {
                idKey:'tag_id',
                pIdKey:'parent_id',
                rootPId:0,
                enable: true
            }
        }
    };
    $.fn.zTree.init($("#treeTag"), setting, page_params.data_tag);
    zTree = $.fn.zTree.getZTreeObj("treeTag");
    zTree.expandAll(true);
    //搜索按钮
    $("#btn-search").on('click', function () {
        table.bootstrapTable('refresh');
    });
    //设置黑名单
    function setBlack(openids, is_lock) {
        let title = '';
        let remark = '';
        if (is_lock){
            title = '确认加入黑名单?';
            remark = '加入黑名单后，你将无法接收该用户发来的消息，且该用户无法接收公众号发出的消息，无法参与留言和赞赏';
        }else{
            title = '确定恢复用户？';
            remark = '恢复用户后将恢复所有正常功能';
        }
        utils.confirm(page_params.url_setblack, {
            openids:openids, is_lock:is_lock,
        },(response, postdata) => {
            data = response.data;
            utils.showToastr(data);
            if (data.status == 'success') {
                table.bootstrapTable('refresh');
            }
        },title, remark);
    }
    //批量添加黑名单
    $("#btn-addblack").on('click', function () {
        var checkedlist = table.bootstrapTable('getSelections');
        if (checkedlist.length <= 0){
            layer.alert('请选择打标签的用户', {title: '友情提示', icon: 2});
        }
        var openids = [];
        $.each(checkedlist, function (i, user) {
            openids.push(user.openid);
        })
        setBlack(openids, 1);
    });
    //提交表单
    $("#box-remark .btn-sub").on('click', function () {
        utils.ajaxSubmitForm($("#box-remark form"), '', {}, (response, postdata) => {
            data = response.data;
            utils.showToastr(data);
            if (data.status == 'success') {
                layer.close(box);
                table.bootstrapTable('refresh');
            }
        });
    });
    //批量打标签
    $("#btn-addtag").on('click', function () {
        var checkedlist = $('#table').bootstrapTable('getSelections');
        if (checkedlist.length <= 0){
            layer.alert('请选择打标签的用户', {title: '友情提示', icon: 2});
            return false;
        }
        let openids = [];
        $.each(checkedlist, function (i, user) {
            openids.push(user.openid);
        })
        $("#box-tag form").resetForm();
        $("#box-tag form").attr('action', page_params.url_addtag);
        $("#box-tag input[name='openids']").val(openids.join(','));
        //取消选中
        zTree.checkAllNodes(false);
        box = layer.open({
            type: 1,
            title: '批量打标签',
            anim: 2,
            shadeClose: true, //开启遮罩关闭
            skin: 'layui-layer-molv', //加上边框
            area: ['500px', '400px'], //宽高
            content: $('#box-tag')
        });
    });
    //标签保存
    $("#box-tag .btn-sub").on('click', function () {
        //已选权限
        //var checkedNode = $("#jstree").jstree('get_checked');
        let tagIds = [];
        var zTree = $.fn.zTree.getZTreeObj("treeTag");
        var nodes = zTree.getCheckedNodes(true);
        $.each(nodes, function (n, value) {
            tagIds.push(value.wx_tag_id);
        });
        utils.ajaxSubmitForm($("#box-tag form"), '', {tagIds:tagIds}, (response, postdata) => {
            data = response.data;
            utils.showToastr(data);
            if (data.status == 'success') {
                layer.close(box);
                table.bootstrapTable('refresh');
            }
        });
    });
    //同步用户
    $("#btn-sync").on('click', function () {
        utils.confirm(page_params.url_sync, {}, (response, postdata) => {
            data = response.data;
            utils.showToastr(data);
            if (data.status == 'success') {
                table.bootstrapTable('refresh');
            }
        },'你确定同步所有用户数据么？', '该同步过程可能花费大量时间');
    });
    //同步黑名单
    $("#btn-syncblack").on('click', function () {
        utils.confirm(page_params.url_syncblack, {}, (response, postdata) => {
            data = response.data;
            utils.showToastr(data);
            if (data.status == 'success') {
                table.bootstrapTable('refresh');
            }
        },'你确定黑名单用户么？', '该同步过程可能花费大量时间');
    });
});